<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加分类按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCategory">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 分类表格 -->
      <tree-table
        class="treeTable"
        :data="categoryList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        index-text="#"
        border
        :show-row-hover="false"
      >
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: #1ddc03"
          ></i>
          <i class="el-icon-error" v-else style="color: #a71e1e"></i>
        </template>
        <template slot="sort" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            type="success"
            size="mini"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <template slot="option" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCategory(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteCategory(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.getCategoryParams.pagenum"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="this.getCategoryParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="categoryTotal"
      >
      </el-pagination>
      <!-- 添加分类对话框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="addCategoryDialogVisible"
        width="50%"
        @close="closeAddCategoryDialog"
      >
        <el-form
          :model="addCategoryForm"
          :rules="addCategoryRules"
          ref="addCategoryRef"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCategoryForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <el-cascader
              v-model="currentCategory"
              :options="categoryCascaderOption"
              :props="categoryCascaderProps"
              @change="categoryCascaderChange"
              clearable
              ref="categoryCascaderRef"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sendAddCategory">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改分类对话框 -->
      <el-dialog
        title="修改分类"
        :visible.sync="editCategoryDialogVisible"
        width="50%"
        @close="$refs.editCategoryRef.clearValidate()"
      >
        <el-form
          :model="editCategoryForm"
          :rules="editCategoryRules"
          ref="editCategoryRef"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editCategoryForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCategoryDialogVisible = false"
            >取 消</el-button
          >
          <el-button type="primary" @click="sendEditCategory">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  created () {
    this.getCategoryList()
  },
  data () {
    return {
      // 商品分类请求参数对象
      getCategoryParams: {
        type: '',
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类数据列表
      categoryList: [],
      // 商品分类数据总条数
      categoryTotal: 0,
      // 商品分类表格列配置
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk'
        },
        {
          label: '排序',
          type: 'template',
          template: 'sort'
        },
        {
          label: '操作',
          type: 'template',
          template: 'option'
        }
      ],
      // 添加分类对话框开启和关闭
      addCategoryDialogVisible: false,
      // 添加分类的表单数据
      addCategoryForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 添加分类的表单数据验证规则
      addCategoryRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      //   父级分类选中项 id
      currentCategory: [],
      //   父级分类选项数据数组
      categoryCascaderOption: [],
      //   父级分类 props 配置
      categoryCascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: 'true'
      },
      //   修改分类对话框开启与隐藏
      editCategoryDialogVisible: false,
      // 修改分类的表单数据
      editCategoryForm: {},
      // 修改分类的表单数据规则
      editCategoryRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 发送请求获取商品分类数据
    async getCategoryList () {
      let { data: res } = await this.$http.get('categories', {
        params: this.getCategoryParams
      })
      //   console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.categoryList = res.data.result
      this.categoryTotal = res.data.total
    },
    // 每页显示条数发生改变
    handleSizeChange (size) {
      this.getCategoryParams.pagesize = size
      this.getCategoryParams.pagenum = 1
      this.getCategoryList()
    },
    // 当前页发生变化时
    handleCurrentChange (page) {
      this.getCategoryParams.pagenum = page
      this.getCategoryList()
    },
    // 点击添加分类按钮事件
    addCategory () {
      this.addCategoryDialogVisible = true
      this.getCascaderCategory()
    },
    // 关闭添加分类对话框重置表单
    closeAddCategoryDialog () {
      this.$refs.addCategoryRef.resetFields()
      this.currentCategory = []
      this.addCategoryForm.cat_pid = 0
      this.addCategoryForm.cat_level = 0
    },
    // 获取父级分类级联选择器数据
    async getCascaderCategory () {
      let { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.categoryCascaderOption = res.data
    },
    // 父级分类级联选择器选项发生变化
    categoryCascaderChange () {
      if (this.currentCategory.length > 0) {
        this.addCategoryForm.cat_pid =
          this.currentCategory[this.currentCategory.length - 1]
        this.addCategoryForm.cat_level = this.currentCategory.length
      } else {
        this.addCategoryForm.cat_pid = 0
        this.addCategoryForm.cat_level = 0
      }
    },
    // 提交添加分类请求
    sendAddCategory () {
      this.$refs.addCategoryRef.validate(async (valid) => {
        if (!valid) return
        let { data: res } = await this.$http.post(
          'categories',
          this.addCategoryForm
        )
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addCategoryDialogVisible = false
        this.getCategoryList()
      })
    },
    // 点击修改分类按钮
    async editCategory (category) {
      this.editCategoryDialogVisible = true
      let { data: res } = await this.$http.get('categories/' + category.cat_id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editCategoryForm = res.data
    },
    // 提交修改分类请求
    sendEditCategory () {
      this.$refs.editCategoryRef.validate(async (valid) => {
        if (!valid) return
        let { data: res } = await this.$http.put(
          'categories/' + this.editCategoryForm.cat_id,
          { cat_name: this.editCategoryForm.cat_name }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        console.log(res)
        this.$message.success(res.meta.msg)
        this.getCategoryList()
        this.editCategoryDialogVisible = false
      })
    },
    // 点击删除分类按钮
    async deleteCategory (category) {
      let confirm = await this.$messageBox
        .confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .catch((err) => err)
      if (confirm !== 'confirm') return this.$message('已取消删除')
      let { data: res } = await this.$http.delete(
        'categories/' + category.cat_id
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getCategoryList()
    }
  }
}
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
